<?php
namespace app\helpers;

use Yii;
use yii\helpers\Json;
use GuzzleHttp\Client;
use GuzzleHttp\json_decode;
use app\helpers\ApiCode as helperApiCode;
use app\helpers\Logger as helperLogger;
use app\helpers\Common as helperCommon;
use app\models\Login as mLogin;

class Http{

    const GET = 'GET';
    const POST = 'POST';
    const DELETE = 'DELETE';
    const PUT = 'PUT';
    const OPTION = 'OPTIONS';
    const PATCH = 'PATCH';

    //api  日志 标识
    const LOG_ID_REQUEST    = 'api_request';
    const LOG_ID_RESPONSE   = 'api_reponse';

    // CuzzleHttp\Client
    private $_client = null;

    /** {{{ __construct($config)
     * @param $config = [] Components::__construct($config)
     */
    public function __construct(){

        $this->_client = new Client();
    }

    public function getClient()
    {
        return $this->_client;
    }

    /**
     *
     * @param $config
     * @return new Client($config);
     */
    public function getInstanceWithConfig($config = [])
    {
        $this->_client = new Client($config);
        return $this->_client;
    }

    /**
     * API 请求入口函数
     * @param string $method : post|get|put...
     * @param string $url : http请求url
     * @param array $params : 请求参数
     */
    public function request($method, $url, $params = []){

        //请求参数处理
        $params = $this->assembleParams($method, $params);
        //log 请求参数
        $jsonParams = Json::encode($params);
        $reqInfo = "!! method:$method | url:[$url] | $jsonParams ~!!";
        yii::info($reqInfo ,self::LOG_ID_REQUEST);
        //request
        $response = $this->_client->request($method, $url, $params);
        //response
        $statusCode = $response->getStatusCode();
        $responseBody = $response->getBody()->__toString();
        yii::info('!! ' . $responseBody . ' ~!!',self::LOG_ID_RESPONSE);

        return $this->response($responseBody);

    }

    /**
     * 解析接口返回数据
     * @param <string> $responseJson : 接口返回数据
     */
    public function response($responseJson){

        $res = json_decode($responseJson,true);
        $status = '';
        $ret = [];
        $ret['status'] = !empty($res['status']) ? $res['status'] : helperApiCode::API_CODE_ERROR;
        $ret['message'] = @helperApiCode::trans($ret['status'],$res['message'] ? $res['message'] : $res['msg'] ? $res['msg'] : '');
        $ret['data'] = !empty($res['data']) ? $res['data'] : '';

        return $ret;
    }

    /**
     * 解析接口返回数据
     * @param <string> $responseJson : 接口返回数据
     */
    public function message($codeStatus){
        return [
            'status' => $codeStatus,
            'message' => helperApiCode::trans($codeStatus),
            'data' => '',
        ];
    }

    /**
     * 拼接url,
     * @param unknown $path
     * @param unknown $webroot
     * @return string
     */
    public function assembleUrl($path,$domain = '')
    {
        $path = trim($path, '/');
        $rooturl = trim(Yii::$app->params['api']['rooturl'],'/');
        $rooturl = $domain ?: $rooturl;
        return $rooturl . "/$path";
    }

    /**
     * 记录请求日志
     * @param string $logStr: 日志内容
     * @param string $fname: 文件名
     */
    public function log($logStr,$fname = 'http'){

        helperLogger::write($logStr,$fname);
    }

    /**
     * 参数处理
     * @param string $method
     * @param array $params
     * @param boolean $initPublicParam : 公用参数添加,默认添加
     */
    private function assembleParams($method,$params = []){
        $method = strtoupper($method);
        $ps = [];

        if ($method == self::GET) {

            $ps['query'] = $params;
        } else {
            $ps['form_params'] = $params;
        }
        return $this->assembleHeader($method, $ps);
    }

    /** {{{ 组合自定义内嵌的header
     */
    private function assembleHeader($method, $params = [])
    {
        return $params;
    }

}